package com.star.mianshidog.limiter;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;

/**
 * packageName com.star.mianshidog.limiter
 *
 * @author zerostart
 * @className RequestRateLimiter
 * @date 2024/11/13
 * @description   统计访问频率=====单机
 */
public class RequestRateLimiter {


    private ConcurrentHashMap<String, LongAdder> userRequestCounts = new ConcurrentHashMap<>();

    private final long interval;


    public RequestRateLimiter(long interval) {
        this.interval = interval;
    }


    /**
     * 用户访问时调用此方法
     * @param userId
     */
    public void RecordRequest(String userId) {
        userRequestCounts.computeIfAbsent(userId, k -> new LongAdder()).increment();
    }

    public long getRequestCount(String userId) {
        return userRequestCounts.getOrDefault(userId, new LongAdder()).sum();
    }


    public void startRestTask() {
        new Thread(()-> {
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(interval);  //等待指定的时间间隔
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
                userRequestCounts.clear();
            }
        }).start();
    }

}
